import Request from '@/common/luch-request/index.js'
import {ACCESS_TOKEN} from '@/common/util/constants.js'
import configService from './config.service.js'
import tip from '@/common/util/tip.js';
// import store from '@/store/index.js';
import { objectToRouteParams } from '@/common/util/util'

let apiUrl = configService.apiUrl;
let isSkipLogin = ''

const getTokenStorage = () => {
	let token = ''
	try{
		token = uni.getStorageSync(ACCESS_TOKEN)
	}catch(e){
		//TODO handle the exception
		console.log("getTokenStorage",token)
	}
	return token
}



const http = new Request()
http.setConfig((config) => { /* 设置全局配置 */
  config.baseUrl = apiUrl /* 根域名不同 */
  config.header = {
    ...config.header
  }
  return config
})

/**
 * 自定义验证器，如果返回true 则进入响应拦截器的响应成功函数(resolve)，否则进入响应拦截器的响应错误函数(reject)
 * @param { Number } statusCode - 请求响应体statusCode（只读）
 * @return { Boolean } 如果为true,则 resolve, 否则 reject
 */
// 有默认，非必写
http.validateStatus = (statusCode) => {
  return statusCode === 200
}

http.interceptor.request((config, cancel) => { /* 请求之前拦截器 */
	// uni.showLoading({
	// 	title:'加载中...'
	// })
  config.header = {
    ...config.header,
     'u2at':getTokenStorage()
  }
  
  /*if (!token) { // 如果token不存在，调用cancel 会取消本次请求，但是该函数的catch() 仍会执行
    cancel('token 不存在') // 接收一个参数，会传给catch((err) => {}) err.errMsg === 'token 不存在'
  }*/
  
  return config
})

// 必须使用异步函数，注意
http.interceptor.response(async (response) => { /* 请求之后拦截器 */
  if (response.data.code !== 200) {  // 服务端返回的状态码不等于200，则reject()
	if (response.data.code == 401) {
		let pages = getCurrentPages()
		const backRoute = pages.length && pages[pages.length - 1]
		if(Object.keys(backRoute)){
			const options = backRoute.options || {}
			const query = objectToRouteParams(options)
			const url = Object.keys(options).length ? `/${backRoute.route}?${query}` : `/${backRoute.route}`
			uni.setStorageSync('origin', url)
		}
		isSkipLogin = response.data.code
		// #ifdef MP-WEIXIN
		uni.showLoading({})
		setTimeout(function() {
			uni.redirectTo({
				url: '/pages/login/login?path=' + encodeURIComponent(response.data.data),
				complete() {
					console.log('完成跳转')
					uni.hideLoading()
				}
			});
		}, 200)
		
		// #endif
		// #ifdef H5 
			window.location.href = response.data.data+'&redirect_uri='+window.location.href
		// #endif
		
	} else if(response.data.code == 500){
		uni.showToast({
			title: response.data.msg,
			icon: 'none',
			mask: true,
			duration:1000
		})
		return Promise.reject(response.data)
	} else {
		return Promise.reject(response.data)
	}
  }
  isSkipLogin = response.data.code
  // uni.hideLoading()
  return response.data
}, (response) => {
	// uni.hideLoading()
	// 请求错误做点什么
  console.log("请求错误做点什么");
  if (response) {
      tip.error({
        duration: 0,
        forbidClick: true,
        message: response.data.msg
      });
    return response
  }
  return response
})

export {
  http
}
